

export const throttle = (fn, wait, immediate) => {
	let timer, timeStamp=0;
	let context, args;
	let run = () => {
		timer=setTimeout(()=>{
			if(!immediate){
				fn.apply(context,args);
			}
			clearTimeout(timer);
			timer=null;
		},wait);
	}
 
	return function () {
		context=this;
		args=arguments;
		if(!timer){
			if(immediate){
				fn.apply(context,args);
			}
			run();
		}
	}
 
}

// 增加前缘触发功能
export const debounce = (fn, wait, immediate=false) => {
	let timer, startTimeStamp=0;
	let context, args;
 
	let run = (timerInterval)=>{
		timer= setTimeout(()=>{
			let now = (new Date()).getTime();
			let interval=now-startTimeStamp
			if(interval<timerInterval){ // the timer start time has been reset，so the interval is less than timerInterval
				startTimeStamp=now;
				run(wait-interval);  // reset timer for left time 
			}else{
				if(!immediate){
					fn.apply(context,args);
				}
				clearTimeout(timer);
				timer=null;
			}
			
		},timerInterval);
	}
 
	return function(){
		context=this;
		args=arguments;
		let now = (new Date()).getTime();
		startTimeStamp=now; // set timer start time
 
		if(!timer){
			if(immediate) {
				fn.apply(context,args);
			}
			run(wait);    // last timer alreay executed, set a new timer
		}
	}
 
}

/**
 * @param{String} time: 给出的时间 -> 2020年11月18日 11:58
 */
export const timeFormat = (time) => {
	const curTime = new Date();
	const timeReg = new RegExp('[年月日:]')
	
	let [year, month, day, hour, min] = time.split(timeReg)
				.map(time => +time);
	if(year !== curTime.getFullYear()) {
		return time;
	}
	if(min < 10) {
		min = `0${min}`
	}
	if(	month !== curTime.getMonth()+1 || 
		day !== curTime.getDate()) {
		return `${month}月${day}日 ${hour}:${min}`;
	}
	return `${hour}:${min}`
}






